<?php
/**
 * Created by PhpStorm.
 * User: xuho
 * Date: 2020-09-05
 * Time: 16:54
 */

namespace extend\payment;


class FuYouAuthService
{
    /**
     * @param $request
     * @return mixed
     * @throws \Exception
     */
    public function openidByService($request)
    {
        // 获取支付参数
        $paramSign = $this->beforeRequest2($request);
        // 接口地址
        $urlApi = '/oauth2/getOpenid';

        // 必填数据
        $paramSign['redirect_uri'] = $request['redirect_uri'];
        $paramSign['type'] = '1';

        // 非必填数据
        $paramSign['appid'] = $request['appid'] ?? '';

//        $response = $this->sendRequest($urlApi, $paramSign);
        $response = $this->sendRequest2($urlApi, $paramSign);
        return $this->afterRequest($response);
    }

    public function openidByAuth($request)
    {
        // 获取支付参数
        $paramSign = $this->beforeRequest2($request);
        // 接口地址
        $urlApi = '/auth2Openid';

        // 必填数据
//        $paramSign['type'] = '1';
        $paramSign['auth_code'] = $request['auth_code'];

        // 非必填数据
        $paramSign['order_type'] = $request['order_type'] ?? '';
        $paramSign['order_amt'] = $request['order_amt'] ?? '';
        $paramSign['sub_appid'] = $request['sub_appid'] ?? '';

//        $response = $this->sendRequest($urlApi, $paramSign);
        $response = $this->sendRequest($urlApi, $paramSign);
        return $this->afterRequest($response);
    }


    public function beforeRequest2($request = [], $type = 'order')
    {
        $this->domain = $request['domain'];
        $this->privateKey = $request['private_key'];

        // 商户号
        $paramSign['mchnt_cd'] = $request['mchnt_cd'];
        // 机构号
        $paramSign['ins_cd'] = $request['ins_cd'];


//        $paramSign['version'] = '1.0';
//        $paramSign['term_ip'] = $request['term_ip'];
//        $paramSign['random_str'] = nonceStr();

        return $paramSign;
    }


    public function afterRequest($response)
    {
        $response = xml2array($response);
        var_dump($response);
        exit;
        $response = json_decode($response, true);

        var_dump($response);
    }
}